package cn.enilu.flash.api.controller;

import cn.enilu.flash.bean.dto.OptionDto;
import cn.enilu.flash.bean.dto.OptionObjDto;
import cn.enilu.flash.bean.vo.front.Rets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @Description
 * @Author Spark
 * @Date Created in (2019/10/30 8:39)
 * @Version v1.0
 * @Modify
 **/
@RestController
public class OptionController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(OptionController.class);
    private static String PCK = "cn.enilu.flash.enums.body.";

    @GetMapping(value = "/option/{name}")
    public Object get(@PathVariable("name") String name) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        if(StringUtils.isBlank(name)){
            return Rets.failure("字典名称不能为空");
        }
        String[] names = name.split("_");
        String clzName;
        Class clzz;
        Field field;
        Map<Integer, String> m;
        OptionDto od = new OptionDto();
        for (String s : names) {
            clzName = PCK + s;
            clzz = Class.forName(clzName);
            field = clzz.getField("toMap");
            OptionObjDto oo;
            List<OptionObjDto> list = new ArrayList<>();
            m = (Map<Integer, String>)field.get(clzz);
            Iterator<Map.Entry<Integer, String>> entries = m.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<Integer, String> entry = entries.next();
                oo = new OptionObjDto();
                oo.setK(entry.getKey());
                oo.setV(entry.getValue());
                list.add(oo);
            }
            od.getMaps().put(s, list);

        }
        return Rets.success(od);
    }
}
